<template>
  <div class="print_basic">
    <div style="display: flex;justify-content: space-between;margin-bottom: 10px;height: 30px;">
      <el-dropdown placement="bottom-start" @command="dropdownChange">
        <span class="el-dropdown-link">
          {{ activeName || '模板选择' }}
          <i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <el-dropdown-menu
          slot="dropdown"
          style="max-height: 500px;overflow: hidden;overflow-y: scroll;"
        >
          <el-dropdown-item v-for="item in templateOptions" :command="item.id" :key="item.id">
            <span :style="{ 'color': activeId == item.id ? '#1b93f9' : '' }">{{ item.name }}</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <div>
        <el-button size="mini" type="primary" @click="saveTemplate">保存</el-button>
        <el-button size="mini" type="danger" @click="deleteTemplate" v-if="activeId">删除</el-button>
      </div>
    </div>
    <a-card :bordered="false" style="flex: 1;">
      <div class="card_view">
        <div class="edit_view" :style="{ height: maxHeight + 'px' }">
          <div v-for="(item, index) in styleData" :key="item.sort">
            <div
              :class="[item.sort == 1 ? 'edit_item_head_first' : 'edit_item_head']"
              @click="item.unfold = !item.unfold"
            >
              <span>{{ item.title }}</span>
              <i v-if="item.unfold" class="el-icon-caret-top"></i>
              <i v-else class="el-icon-caret-bottom"></i>
            </div>
            <!-- 模板名称 -->
            <div class="content_view" v-if="item.unfold">
              <div v-if="item.sort == 1">
                <div style="display: flex;align-items: center;margin-bottom: 10px;"
                  v-if="!isBill">
                  <div>模板类型</div>
                  <div style="flex: 1; margin-left: 10px;">
                    <el-select v-model="item.type" placeholder="请选择" @change="templateChange">
                      <el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                  </div>
                </div>
                <el-input
                  type="textarea"
                  placeholder="请输入内容"
                  v-model="item.name"
                  maxlength="20"
                  show-word-limit
                ></el-input>
                <div style="display: flex;align-items: center;justify-content: space-between;margin-top: 10px;">
                  <div>设为默认模板</div>
                  <el-checkbox v-model="item.isDefault"></el-checkbox>
                </div>
              </div>
              <!-- 纸张尺寸 -->
              <div v-if="item.sort == 2">
                <div v-for="subItem in item.type" class="paper_class">
                  <span>{{ subItem.lx }}</span>
                  <el-checkbox v-model="subItem.selected" @change="paperTypeClick(item, subItem)"></el-checkbox>
                </div>
                <div v-for="subItem in item.direction" class="paper_class">
                  <span>{{ subItem.lx }}</span>
                  <el-checkbox
                    v-model="subItem.selected"
                    @change="paperDirectionClick(item, subItem)"
                  ></el-checkbox>
                </div>
              </div>
              <!-- 单据样式 -->
              <div v-if="item.sort == 3">
                <!-- logo -->
                <div class="paper_class" style="border-bottom: #ddd 6px solid;">
                  <span>logo</span>
                  <div style="display: flex;align-items: center;">
                    <el-upload
                      class="upload-demo"
                      :action="uploadAction"
                      :on-success="(value) => handleSuccess(value, 'logo')"
                      :file-list="fileList"
                      :headers="headers"
                      :show-file-list="false"
                    >
                      <i
                        class="el-icon-upload2"
                        style="font-size: 20px;margin-right: 20px;font-weight: 800;color: #00C42D;"
                      ></i>
                    </el-upload>
                    <el-checkbox v-model="item.logo.selected"></el-checkbox>
                  </div>
                </div>
                <!-- 标题 -->
                <div style="border-bottom: #ddd 6px solid;padding-bottom: 10px;">
                  <div
                    style="display: flex;align-items: center;margin: 10px 0;justify-content: space-between;"
                  >
                    <div>标题</div>
                    <div style="display: flex;">
                      <el-select
                        v-model="item.titleStyle.size"
                        placeholder="请选择"
                        style="width: 60px;"
                      >
                        <el-option
                          v-for="item in fontSizeOptions"
                          :key="item"
                          :label="item + '号'"
                          :value="item"
                        ></el-option>
                      </el-select>
                      <div
                        style="margin-left: 6px;"
                        :class="[item.titleStyle.bold ? 'font_bold active' : 'font_bold']"
                        @click="item.titleStyle.bold = !item.titleStyle.bold"
                      >B</div>
                      <div
                        style="margin-left: 6px;"
                        :class="[item.titleStyle.underline ? 'font_bold active' : 'font_bold']"
                        @click="item.titleStyle.underline = !item.titleStyle.underline"
                      >
                        <span style="text-decoration:underline">U</span>
                      </div>
                    </div>
                  </div>
                  <el-input
                    type="textarea"
                    placeholder="请输入内容"
                    v-model="item.titleStyle.content"
                    maxlength="40"
                    :autosize="{ minRows: 3, maxRows: 4 }"
                    show-word-limit
                  ></el-input>
                </div>
                <!-- 副标题 -->
                <div style="border-bottom: #ddd 6px solid;padding-bottom: 10px;">
                  <div
                    style="display: flex;align-items: center;margin: 10px 0;justify-content: space-between;"
                  >
                    <div>副标题</div>
                    <div style="display: flex;">
                      <el-select
                        v-model="item.subTitleStyle.size"
                        placeholder="请选择"
                        style="width: 60px;"
                      >
                        <el-option
                          v-for="item in fontSizeOptions"
                          :key="item"
                          :label="item + '号'"
                          :value="item"
                        ></el-option>
                      </el-select>
                      <div
                        style="margin-left: 6px;"
                        :class="[item.subTitleStyle.bold ? 'font_bold active' : 'font_bold']"
                        @click="item.subTitleStyle.bold = !item.subTitleStyle.bold"
                      >B</div>
                      <div
                        style="margin-left: 6px;"
                        :class="[item.subTitleStyle.underline ? 'font_bold active' : 'font_bold']"
                        @click="item.subTitleStyle.underline = !item.subTitleStyle.underline"
                      >
                        <span style="text-decoration:underline">U</span>
                      </div>
                    </div>
                  </div>
                  <el-input
                    type="textarea"
                    placeholder="请输入内容"
                    v-model="item.subTitleStyle.content"
                    maxlength="20"
                    show-word-limit
                  ></el-input>
                </div>
                <!-- 单据表头 -->
                <div style="border-bottom: #ddd 1px solid;">
                  <div
                    style="display: flex;align-items: center;margin: 10px 0;justify-content: space-between;"
                  >
                    <div>单据表头</div>
                    <div style="display: flex;">
                      <el-select
                        v-model="item.tableHead.size"
                        placeholder="请选择"
                        style="width: 60px;"
                      >
                        <el-option
                          v-for="item in fontSizeOptions"
                          :key="item"
                          :label="item + '号'"
                          :value="item"
                        ></el-option>
                      </el-select>
                      <div
                        style="margin-left: 6px;"
                        :class="[item.tableHead.bold ? 'font_bold active' : 'font_bold']"
                        @click="item.tableHead.bold = !item.tableHead.bold"
                      >B</div>
                    </div>
                  </div>
                </div>
                <!-- 单据内容 -->
                <div
                  style="display: flex;align-items: center;margin: 10px 0;justify-content: space-between;"
                >
                  <div>单据内容</div>
                  <div style="display: flex;">
                    <el-select v-model="item.tableBody.size" placeholder="请选择" style="width: 60px;">
                      <el-option
                        v-for="item in fontSizeOptions"
                        :key="item"
                        :label="item + '号'"
                        :value="item"
                      ></el-option>
                    </el-select>
                    <div
                      style="margin-left: 6px;"
                      :class="[item.tableBody.bold ? 'font_bold active' : 'font_bold']"
                      @click="item.tableBody.bold = !item.tableBody.bold"
                    >B</div>
                  </div>
                </div>
              </div>
              <!-- 表格行设置 -->
              <div v-if="item.sort == 4">
                <div class="paper_class" style="border: none">
                  <span class="singleLine">表头行高</span>
                  <!-- <el-input v-model="item.headHeight" min="20" type="number" style="width: 60px;"></el-input> -->
                  <span>自适应</span>
                </div>
                <div class="paper_class" style="border: none">
                  <span class="singleLine">表内行高</span>
                  <!-- <el-input v-model="item.rowHeight" min="20" type="number" style="width: 60px;"></el-input> -->
                  <span>自适应</span>
                </div>
                <div class="paper_class" style="border: none">
                  <span class="singleLine">表尾行高</span>
                  <!-- <el-input v-model="item.footHeight" min="20" type="number" style="width: 60px;"></el-input> -->
                  <span>自适应</span>
                </div>
                <!-- <div class="paper_class" style="border: none">
                  <span class="singleLine">固定行数</span>
                  <el-input v-model="item.rowCount" type="number" style="width: 60px;"></el-input>
                </div> -->
              </div>
              <!-- 单据头部 -->
              <div v-if="item.sort == 5">
                <div
                  v-for="subItem in styleData[4].columnData"
                  class="paper_class"
                  style="border: none;"
                >
                  <span>{{ subItem.name }}</span>
                  <el-checkbox v-model="subItem.selected"></el-checkbox>
                </div>
              </div>
              <!-- 单据明细 -->
              <div v-if="item.sort == 6">
                <div
                  v-for="subItem in styleData[5].columnData"
                  class="paper_class"
                  style="border: none;"
                >
                  <span>{{ subItem.morenName }}</span>
                  <div style="display: flex;align-items: center;">
                    <el-input
                      v-model="subItem.width"
                      type="number"
                      style="width: 60px;margin-right: 10px;"
                    ></el-input>
                    <el-checkbox v-model="subItem.morenState"></el-checkbox>
                  </div>
                </div>
              </div>
              <!-- 单据尾部 -->
              <div v-if="item.sort == 7">
                <div
                  v-for="subItem in styleData[6].columnData"
                  class="paper_class"
                  style="border: none;"
                >
                  <span>{{ subItem.name }}</span>
                  <el-checkbox v-model="subItem.selected"></el-checkbox>
                </div>
              </div>
              <!-- 底部二维码 -->
              <div v-if="item.sort == 8">
                <div v-for="subItem in item.qrList" class="paper_class" style="border: none">
                  <el-input
                    v-if="subItem.titleEdit"
                    v-model="subItem.title"
                    style="margin-right: 10px;"
                  ></el-input>
                  <span class="singleLine" v-else>{{ subItem.title }}</span>
                  <div style="display: flex;align-items: center;">
                    <i
                      class="el-icon-edit-outline"
                      style="font-size: 20px;margin-right: 12px;font-weight: 600;color: #00C42D;"
                      @click="qrTitleEdit(item, subItem)"
                    ></i>
                    <el-upload
                      class="upload-demo"
                      :action="uploadAction"
                      :on-success="(value) => handleSuccess(value, 'qr' + subItem.id)"
                      :file-list="fileList"
                      :headers="headers"
                      :show-file-list="false"
                    >
                      <i
                        class="el-icon-upload2"
                        style="font-size: 20px;margin-right: 20px;font-weight: 800;color: #00C42D;"
                      ></i>
                    </el-upload>
                    <el-checkbox v-model="subItem.selected"></el-checkbox>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="preview_view">
          <printSettlement :baseData="styleData" ref="print"></printSettlement>
        </div>
      </div>
    </a-card>
    <!-- 提醒弹框 -->
    <DialogSimplePrompt ref="simplePrompt" @onSure="onSureSimple"></DialogSimplePrompt>
  </div>
</template>
<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import printStyle from '@/components/c_print/printStyleSettlement'
import printSettlement from '@/components/c_print/printSettlement'
import DialogSimplePrompt from '@/views/components/dialogSimplePrompt'
import { getAction, postAction, putAction, downPostFile } from '@/api/manage'
import {
  handlePermissions,
  handleOtherPerms,
  sysConfig,
  getSystemParamsByName,
  formatMoney,
  formatPrice,
  formatNumber,
  delcommafy,
  handleArrayToObject,
  handleObjectToArray,
  formatHundredMillionPrice
} from '@/utils/index'
export default {
  name: 'printSetSettlement',
  props: {
    tipsData: Object,
  },
  components: {
    printSettlement,
    DialogSimplePrompt
  },
  data () {
    return {
      styleData: [],
      options: [], //模板类型
      filterOptions: [], //需要筛选类型
      fontSizeOptions: [
        10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30,
      ],
      billData: {},
      maxHeight: 100,
      templateOptions: [],
      uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
      headers: { "X-Access-Token": Vue.ls.get(ACCESS_TOKEN) },
      fileList: [],
      baseSourse: [],
      activeId: '',
      activeName: '',
      isBill: false, // 是否从对应的单据跳转过来的
    }
  },
  activated() {
    console.log('printSetSettlement activated');

    let query = this.$route.params
    console.log('query=', query);
    if (query && query.val) {
      let type = query.type
      let billType = this.styleData[0].type
      if ((type == 'edit' && this.activeId == query.tlId) || (type == 'add' && billType == query.val)) {
        //由于路由缓存机制，设置相同模板或新增相同单据模板时不再更新页面数据
        return
      }
      this.filterOptions = [query.val]
      this.styleData[0].type = query.val
      this.templateChange(query.val)
      if (type == 'edit') {
        this.activeId = query.tlId
      }
      this.isBill = true
    } else {
      this.isBill = false
      this.filterOptions = printStyle.billList
    }

    this.getTemplateList()
  },
  deactivated() {
    console.log('printSetSettlement deactivated');
  },
  created () {
    this.styleData = JSON.parse(JSON.stringify(printStyle.baseData))
    this.baseSourse = JSON.parse(JSON.stringify(printStyle.baseData))
    console.log('set=', this.styleData);
    this.options = printStyle.billList

    
  },
  mounted () {
    let that = this
    this.$nextTick(() => {
      let card = document.getElementsByClassName('card_view')
      console.log(card);
      that.maxHeight = card[0].offsetHeight

    })
  },
  methods: {
    handleSuccess (e, val) {
      let url = e.message
      if (val == 'logo') {
        this.styleData[2].logo.url = url
      } else if (val == 'qr1') {
        this.styleData[7].qrList[0].url = url
      } else if (val == 'qr2') {
        this.styleData[7].qrList[1].url = url
      } else if (val == 'qr3') {
        this.styleData[7].qrList[2].url = url
      }

      console.log(e.message);
      // this.ruleForm.avatar = e.message
    },
    async dropdownChange (val) {
      this.activeId = val
      console.log(val);
      for (let index = 0; index < this.templateOptions.length; index++) {
        const element = this.templateOptions[index];
        if (element.id == val) {
          this.activeName = element.name
          let value = JSON.parse(element.value)
          value[0].isDefault = element.isDefault == 1
          this.styleData = value
          return
        }
      }
    },
    templateChange (val) {
      this.styleData = JSON.parse(JSON.stringify(printStyle.baseData))
      this.styleData[0].type = val
      this.activeId = ''
      this.activeName = ''
      console.log(printStyle.bill[val]);
      // 默认单据类型为副标题
      this.styleData[2].subTitleStyle.content = val
      this.billData = printStyle.bill[val]
      this.styleData[4].columnData = this.billData.billHead
      this.styleData[6].columnData = this.billData.billFoot
      this.styleData[5].topColumnData = this.billData.topColumnData

      this.selectTitle(val)
      console.log(this.styleData);
      this.styleData[4].otherData = JSON.parse(JSON.stringify(printStyle.baseData[4].otherData))
    },
    paperTypeClick (item, subItem) {
      let arr = item.type
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index];
        if (element.lx == subItem.lx) {
          element.selected = true
          item.typeValue = element.value
        } else {
          element.selected = false
        }
      }
    },
    paperDirectionClick (item, subItem) {
      let arr = item.direction
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index];
        if (element.lx == subItem.lx) {
          element.selected = true
          item.directionValue = element.lx
        } else {
          element.selected = false
        }
      }
    },
    billHeadClick (item, subItem) {
      subItem.selected = !subItem.selected
    },
    qrTitleEdit (item, subItem) {
      if (subItem.titleEdit) {
        subItem.titleEdit = false
      } else {
        let arr = item.qrList
        for (let index = 0; index < arr.length; index++) {
          const element = arr[index];
          if (element.id == subItem.id) {
            element.titleEdit = true
          } else {
            element.titleEdit = false
          }
        }
      }
    },
    // 查询
    selectTitle (val) {
      getAction('/fieldshowsetting/xghAccountBookFieldShowSetting/getByApiAndAccountBookId', { api: val }).then(res => {
        console.log(res);
        if (res.code == 200) {
          let result = res.result
          let list = []
          if (result && result.fieldSetting) {
            let fieldSetting = JSON.parse(res.result.fieldSetting)
            list = handleObjectToArray(fieldSetting)

          } else {
            list = handleObjectToArray(this.billData.billBody)
          }
          let newList = []
          for (let index = 0; index < list.length; index++) {
            const element = list[index];
            if (element.zidingyiState) {
              if (element.props == 'xghStorehouseId' || element.props == 'xghOutStorehouseId') {
                element.props = element.props + '_dictText'
              }
              newList.push({
                ...element,
                width: 80
              })
            }
          }
          this.styleData[5].columnData = newList
        }
      })
    },
    saveTemplate () {
      let name = this.styleData[0].name
      if (!name) {
        this.$elMessage.warning('请输入模板名称!')
        return
      }
      let orderType = this.styleData[0].type
      let json = JSON.stringify(this.styleData)
      let params = {
        name,
        orderType,
        value: json,
        id: this.activeId,
        isDefault: this.styleData[0].isDefault ? 1 : 0, // 设置默认模版
      }
      let that = this
      let url = this.activeId ? '/xghprinttemplate/xghPrintTemplate/edit' : '/xghprinttemplate/xghPrintTemplate/add'
      postAction(url, params).then(res => {
        if (res.success) {
          this.$elMessage.success(res.message)
          that.styleData = that.baseSourse
          //that.activeId = null // 编辑模版还在该模版页面
          that.activeName = null
          that.getTemplateList()
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 删除模版 
    deleteTemplate () {
      this.$refs.simplePrompt.showTwoBtn('el-icon-warning', '确定要删除当前的模版吗？', '是', '否')
    },
    onSureSimple() {
      let that = this
      getAction('/xghprinttemplate/xghPrintTemplate/delete', {id: this.activeId}).then(res => {
        if (res.success) {
          that.$elMessage.success(res.message ? res.message : '删除成功！')
          that.styleData = that.baseSourse
          // 删除成功,设置显示默认的模版
          let defaultData = that.templateOptions.filter(item => {
            return item.isDefault == 1
          })
          // 设置显示默认的模版
          that.activeId = defaultData.length ? defaultData[0].id : null
          that.activeName = null
          that.getTemplateList()
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    getTemplateList () {
      getAction('/xghprinttemplate/xghPrintTemplate/list', {}).then(res => {
        console.log(res);
        if (res.success) {
          let result = res.result || []
          this.templateOptions = result.filter(item => {
            return this.filterOptions.includes(item.orderType)
          })
          if (this.activeId) {
            this.dropdownChange(this.activeId)
          }
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.print_basic {
  height: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

::v-deep .ant-card-body {
  padding: 10px;
  flex: 1;
  height: 100%;
}

.card_view {
  display: flex;
  width: 100%;
  height: 100%;
}

.edit_view {
  width: 200px;
  font-size: 12px;
  overflow: hidden;
  overflow-y: scroll;

  ::v-deep .el-select {
    height: 30px;
    width: auto;
    box-sizing: border-box;
    // margin-right: 6px;

    .el-input {
      height: 100%;

      .el-input__inner {
        width: 100%;
        height: 100%;
        font-size: 12px;
        padding: 0 12px 0 5px;

        .el-input__suffix-inner {
          height: 100%;
        }
      }

      .el-input__suffix {
        height: 100%;
        width: 20px;
        display: flex;
        align-items: center;
      }
    }
  }

  ::v-deep .el-input {
    height: 30px;

    .el-input__inner {
      width: 100%;
      height: 100%;
      font-size: 12px;
      padding: 0 5px 0 5px;

      .el-input__suffix-inner {
        height: 100%;
      }
    }

    .el-input__suffix {
      height: 100%;
      width: 20px;
      display: flex;
      align-items: center;
    }
  }

  .edit_item_head {
    background: #e6f7ff;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px 8px;
    border-top: #e6f7ff solid 1px;

    span {
      font-size: 14px;
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 600;
      color: #1890fc;
    }

    i {
      color: #1890fc;
    }
  }

  .edit_item_head_first {
    background: #1b93f9;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px 8px;
    border-top: #e6f7ff solid 1px;

    span {
      font-size: 14px;
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 600;
      color: #fff;
    }

    i {
      color: #fff;
    }
  }

  .content_view {
    // animation: graduallymove 1.5s ease-out 0.2s;
    transition: height ease 0.5s; //动画效果
    overflow: hidden;
    padding: 10px 5px;
  }
}

.preview_view {
  flex: 1;
  height: 100%;
  margin-left: 10px;
  background-color: #666666;
  display: flex;
  justify-content: center;
  align-items: center;
}

.paper_class {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 40px;
  border-bottom: #ddd 1px solid;
}

.font_bold {
  background: #ffffff;
  border-radius: 5px;
  border: 1px solid #dddddd;
  width: 30px;
  height: 30px;
  font-weight: 500;
  color: #666666;
  display: flex;
  justify-content: center;
  align-items: center;

  &.active {
    color: #1b94fb;
    border: 1px solid #1b94fb;
  }
}

.singleLine {
  overflow: hidden;
  -webkit-line-clamp: 1;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  margin-right: 10px;
}
</style>
